package com.hee.erp.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hee.erp.filter.LoginContextHolder;
import com.hee.erp.modules.entity.SysRight;
import com.hee.erp.modules.entity.SysUser2Right;
import com.hee.erp.modules.mapper.SysUser2RightMapper;
import com.hee.erp.modules.service.ISysRightService;
import com.hee.erp.modules.service.ISysUser2RightService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.pojo.LoginInfo;
import com.hee.erp.pojo.SysRightTreeNode;
import com.hee.erp.vo.UserRightsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-03-04
 */
@Service
@Transactional
public class SysUser2RightServiceImpl extends ServiceImpl<SysUser2RightMapper, SysUser2Right> implements ISysUser2RightService {

    @Autowired
    ISysRightService sysRightService;

    @Override
    public List<SysRightTreeNode> getRightsByUserId(String userId) {
        LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser2Right::getUserId, userId);
        List<SysUser2Right> user2Rights = this.list(queryWrapper);
        //获取所有的rightId
        List<String> rightIds = user2Rights.stream().map(SysUser2Right::getRightId).collect(Collectors.toList());
        List<SysRightTreeNode> list = sysRightService.getMenuRightsByIds(rightIds);
        return list;

    }

    public List<SysUser2Right> listByUserId(String loginUserId) {
        LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser2Right::getUserId, loginUserId);
        return this.list(queryWrapper);
    }

    @Override
    public List<String> getBtnRightsByRoutePath(String routePath) {
        LoginInfo loginInfo = LoginContextHolder.get();
        String loginUserId = loginInfo.getUserId();
        LambdaQueryWrapper<SysRight> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRight::getRoutePath, routePath);
        SysRight routeRight = sysRightService.getOne(wrapper);
        if (routeRight == null) {
            return null;
        }


        //获取当前登录人配置了哪些权限
        List<SysUser2Right> user2Rights = this.listByUserId(loginUserId);
        List<String> rightIds = user2Rights.stream().map(sysUser2Right -> sysUser2Right.getRightId()).collect(Collectors.toList());

        LambdaQueryWrapper<SysRight> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(SysRight::getParentId, routeRight.getId());
        queryWrapper.eq(SysRight::getType, 1);
        queryWrapper.in(SysRight::getId, rightIds);
        List<SysRight> rights = sysRightService.list(queryWrapper);

        List<String> rightNames = rights.stream().map(sysRight -> sysRight.getRouteName()).collect(Collectors.toList());

        return rightNames;
    }


    @Override
    public List<SysRight> getBigMenuByUserId(String userId) {
        List<SysUser2Right> sysUser2RightList = this.listByUserId(userId);
        List<String> rightIdList = sysUser2RightList.stream().map(e -> e.getRightId()).collect(Collectors.toList());
        List<SysRight> bigMenuList = this.getMenusByRightIdsAndParentId(rightIdList, "0");

        List<SysRight> list = reSortByUserDiy(bigMenuList, sysUser2RightList);
        return list;

    }

    @Override
    public List<SysRight> getShortcutMenuByUserId(String userId) {
        List<SysUser2Right> sysUser2RightList = this.listByUserId(userId);
        List<String> rightIdList = sysUser2RightList.stream()
                .filter(e -> e.getShortcutFlag().equals(1))
                .map(e -> e.getRightId()).collect(Collectors.toList());

        LambdaQueryWrapper<SysRight> queryWrapper = new LambdaQueryWrapper<>();
        if(rightIdList.size() > 0) {
            queryWrapper.in(SysRight::getId, rightIdList);
            List<SysRight> menuList = this.sysRightService.list(queryWrapper);

            List<SysRight> list = menuList.stream().map(e -> {
                SysUser2Right sysUser2Right1 = sysUser2RightList.stream().filter(sysUser2Right -> sysUser2Right.getRightId().equals(e.getId()))
                        .findAny().orElse(new SysUser2Right());
                e.setSortNo(sysUser2Right1.getShortcutSortNo() == null ? 0 : sysUser2Right1.getShortcutSortNo());
                return e;
            }).sorted(Comparator.comparing(SysRight::getSortNo)).collect(Collectors.toList());
            return list;
        }
        return new ArrayList<>(0);


    }

    private List<SysRight> reSortByUserDiy(List<SysRight> originList, List<SysUser2Right> sysUser2RightList) {
        //重新设置排序，根据每个人对菜单的自定义顺序进行排序
        List<SysRight> list = originList.stream().map(e -> {
            SysUser2Right sysUser2Right1 = sysUser2RightList.stream().filter(sysUser2Right -> sysUser2Right.getRightId().equals(e.getId()))
                    .findAny().orElse(new SysUser2Right());

            e.setSortNo(sysUser2Right1.getSortNo() == null ? 0 : sysUser2Right1.getSortNo());
            return e;
        }).sorted(Comparator.comparing(SysRight::getSortNo)).collect(Collectors.toList());

        return list;
    }

    @Override
    public List<SysRight> getMenusByParentIdAndUserId(String userId, String parentId) {
        List<SysUser2Right> sysUser2RightList = this.listByUserId(userId);
        List<String> rightIdList = sysUser2RightList.stream().map(e -> e.getRightId()).collect(Collectors.toList());
        //获取所有的配置了的菜单
        LambdaQueryWrapper<SysRight> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysRight::getId, rightIdList);
        queryWrapper.eq(SysRight::getType, 0);
        List<SysRight> allRightList = sysRightService.list(queryWrapper);

        List<SysRight> list = allRightList.stream().filter(e -> parentId.equals(e.getParentId()))
                .collect(Collectors.toList());
        //根据用户自定义对一级菜单重新设置sortNo,重新排序
        List<SysRight> list1 = reSortByUserDiy(list, sysUser2RightList);
        this.setChildren(list1, allRightList);
        return list1;

    }

    @Override
    public void sort(List<String> ids) {
        String userId = LoginContextHolder.get().getUserId();
        for (int i = 0; i < ids.size(); i++) {
            SysUser2Right sysUser2Right = new SysUser2Right();
            sysUser2Right.setSortNo(i);

            LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser2Right::getUserId, userId);
            queryWrapper.eq(SysUser2Right::getRightId, ids.get(i));

            this.update(sysUser2Right, queryWrapper);

        }
    }

    @Override
    public void setShortcut(@RequestBody List<String> rightIds) {
        String userId = LoginContextHolder.get().getUserId();
        for (int i = 0; i < rightIds.size(); i++) {
            SysUser2Right user2Right = new SysUser2Right();
            user2Right.setShortcutFlag(1);
            user2Right.setShortcutSortNo(i);

            LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser2Right::getUserId, userId);
            queryWrapper.eq(SysUser2Right::getRightId, rightIds.get(i));

            this.update(user2Right, queryWrapper);
        }
    }

    @Override
    public void cancelShortcut(String rightId) {
        String userId = LoginContextHolder.get().getUserId();
        SysUser2Right user2Right = new SysUser2Right();
        user2Right.setShortcutFlag(0);

        LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser2Right::getUserId, userId);
        queryWrapper.eq(SysUser2Right::getRightId, rightId);

        this.update(user2Right, queryWrapper);
    }


    private void setChildren(List<SysRight> list, List<SysRight> allRightList) {
        for (SysRight record : list) {
            List<SysRight> children = allRightList.stream().filter(e -> e.getParentId().equals(record.getId()))
                    .sorted(Comparator.comparing(SysRight::getSortNo))
                    .collect(Collectors.toList());
            if (children != null && children.size() > 0) {
                record.setChildren(children);
                setChildren(children, allRightList);
            }
        }
    }


    private List<SysRight> getMenusByRightIdsAndParentId(List<String> rightIdList, String parentId) {
        LambdaQueryWrapper<SysRight> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(SysRight::getId, rightIdList);
        queryWrapper.eq(SysRight::getParentId, parentId);
        queryWrapper.orderByAsc(SysRight::getSortNo);
        return sysRightService.list(queryWrapper);
    }

    @Override
    public List<String> getRightIdListByUserId(String userId) {
        List<SysUser2Right> sysUser2RightList = this.listByUserId(userId);
        List<String> rightIdList = sysUser2RightList.stream().map(e -> e.getRightId()).collect(Collectors.toList());
        return rightIdList;
    }

    @Override
    public void saveUserRightIdList(UserRightsVo userRightsVo) {
        String userId = userRightsVo.getUserId();
        //找出数据库中当前用户配置的权限id
        List<String> rightIdListByUserId = getRightIdListByUserId(userId);
        List<String> rightIdList = userRightsVo.getRightIdList();


        //比较两个集合，找出新增的权限id
        List<String> addRightIdList = rightIdList.stream().filter(e -> !rightIdListByUserId.contains(e)).collect(Collectors.toList());
        //比较两个集合，找出删除的权限id
        List<String> deleteRightIdList = rightIdListByUserId.stream().filter(e -> !rightIdList.contains(e)).collect(Collectors.toList());

        //新增权限
        if (addRightIdList.size() > 0) {
            addUser2Right(userId, addRightIdList);
        }
        //删除权限
        if (deleteRightIdList.size() > 0) {
            deleteUser2Right(userId, deleteRightIdList);
        }
    }

    private void deleteUser2Right(String userId, List<String> deleteRightIdList) {
        LambdaQueryWrapper<SysUser2Right> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser2Right::getUserId, userId);
        queryWrapper.in(SysUser2Right::getRightId, deleteRightIdList);
        this.remove(queryWrapper);
    }

    private void addUser2Right(String userId, List<String> addRightIdList) {
        List<SysUser2Right> sysUser2RightList = new ArrayList<>();
        for (String rightId : addRightIdList) {
            SysUser2Right user2Right = new SysUser2Right();
            user2Right.setUserId(userId);
            user2Right.setRightId(rightId);

            sysUser2RightList.add(user2Right);
        }

        this.saveBatch(sysUser2RightList);
    }
}
